package com.example.k8s.hello.service.sys.service.impl;


import com.example.k8s.hello.common.exception.ApiExEnum;
import com.example.k8s.hello.service.sys.service.SysCaptchaService;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import com.example.k8s.hello.common.utils.RedisUtils;
import com.example.k8s.hello.bean.sys.constant.SysRedisConstant;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Properties;

/**
 * 验证码
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
//@RequiredArgsConstructor
public class SysCaptchaServiceImpl implements SysCaptchaService {
    private static final DefaultKaptcha producer = new DefaultKaptcha();

    {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        producer.setConfig(config);
    }

    @Override
    public BufferedImage getCaptcha(String uuid) {
        ApiExEnum.A0010.assertTrue(StringUtils.isNotBlank(uuid), "uuid不能为空");
        //生成文字验证码
        String code = producer.createText();

        RedisUtils.set(SysRedisConstant.join(SysRedisConstant.SYS_CAPTCHA, uuid), code, 60 * 5);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        String redisCode = RedisUtils.get(SysRedisConstant.join(SysRedisConstant.SYS_CAPTCHA, uuid));

        if(StringUtils.isBlank(redisCode)){
            return false;
        }

        //删除验证码
        RedisUtils.del(uuid);

        return redisCode.equalsIgnoreCase(code);
    }
}
